import {SingleDownloadTask} from "./SingleDownloadTask";
import {GeneratorFactory} from "../executor/GeneratorFactory";
import {GeneratorExecutor} from "../executor/GeneratorExecutor";
import {FileUtil} from "../../utils/FileUtil";
import {DownloadCenter} from "./DownloadCenter";
import {SqlLibUser} from "../sqlite/service/SqlLibUser";
import {SqlLib} from "../sqlite/SqlLib";
import { dataTool } from "echarts/lib/echarts";
import vm from '../../../src/renderer/content/main'
const POLYV_VIDEO = "PolyvVideo";

export class SetDownloaderLib {

    /**
     * 一组文件的下载器（兼容C#版本，参数命名仿照C#语言）
     * @param downloadParams
     */
    constructor(downloadParams, successCallback, errorCallback) {
        let _this = this;
        this.downloaderId = downloadParams.SetDownloadId;
        this.downloaderInfo = downloadParams.DownloaderInfo;//该课时的详情 {lessonName: "", bookName: "", publisherName: ""}
        this.downloadParames = downloadParams.DownloadParams;
        this.singleDownloadTaskes = [];
        this.errorDownloadTaskIndexes = [];
        this.allFileSize = 0;
        this.currentTotalSize = 0;
        this.currentIndex = 0;
        this.genExecutor = null;

        let promiseArr = []
        //构造函数初始化
        console.log("constructor LessonId::>" + this.downloaderId + " 塞入下载队列的任务个数：" + this.downloadParames.length);
        if(this.downloadParames.length === 0){
            if (successCallback) {
                successCallback();
            }
            return;
        }
        console.log(this.downloadParames);
        this.downloadParames.forEach(downloadParam => {
            let construct = function () {
                return new Promise((resolve, reject) => {
                    let task = new SingleDownloadTask(downloadParam, function () {
                        console.log(task);
                        if (task.fileDownloader.totalSize !== 0) {
                            _this.singleDownloadTaskes.push(task);
                            //获取总文件大小
                            _this.allFileSize += task.fileDownloader.totalSize;
                            window.$log.info("SingleDownloadTask init success downloaderId::> " + task.downloaderId + "downloader type ::> " + downloadParam.FileType);
                            resolve("success");
                        } else {
                            //为0的也push进去
                            _this.singleDownloadTaskes.push(task);
                            console.log('检测到需下载的文件大小为0');
                            window.$log.info("SingleDownloadTask init error downloaderId::> " + task.downloaderId + "downloader type ::> " + downloadParam.FileType);
                            resolve("error");
                        }
                    });
                });
            }
            promiseArr.push(construct);
        });
        let gen = GeneratorFactory.createGenerator(promiseArr);
        let executor = new GeneratorExecutor();
        this.genExecutor = executor
        executor.runWithTimeOut(gen, 60, function () {
            if (successCallback) {
                successCallback();
            }
        }, function () {
            if(errorCallback){
                errorCallback('timeout');
            }
        })
    }

    /**
     * 开始下载的操作
     * @param successCallback
     * @param errorCallback
     * @param progressCallback
     */
    startDownload(successCallback, errorCallback, progressCallback) {
        
        console.log("开始下载一个课时，下载参数：");
        console.log(this.singleDownloadTaskes);
        // return
        let downloadPromise = [];
        let _this = this;
        console.log("2.开始课时的下载！ id::>" + _this.downloaderId);
        if(this.singleDownloadTaskes.length === 0){
            if (successCallback) {
                let successCallbackVal = {
                    ReturnValue: "complete"
                }
                successCallback(JSON.stringify(successCallbackVal));
            }
            return;
        }
        this.singleDownloadTaskes.forEach(async (task, index) => {
            let fileDownloader = null;
            let metaType = task.downloadParam.FileType;
            if (task.downloadParam.FileType === POLYV_VIDEO) {
                console.log('task---------------',task);
                fileDownloader = task.fileDownloader.fileDownloader
            } else {
                fileDownloader = task.fileDownloader;
            }
            fileDownloader.initFileDownloader();
            if (task.fileDownloader.totalSize === 0) {
                //检测到需下载的文件大小为0，直接加入错误索引
                window.$log.error("检测到需下载的文件大小为0，直接加入错误索引 downloadParam --> " + JSON.stringify(task.downloadParam));
                _this.errorDownloadTaskIndexes.push(index)
            } else {
                let downloading = function () {
                    return  new Promise( (resolve, reject) => {
                        fileDownloader.checkDownload(function (result, currentFileSize) {
                            if (result) {
                                fileDownloader.downloadFile(function () {
                                    _this.currentIndex = index;
                                }, function (receivedBytes, nowSpeed) {//下载过程的回调
                                    console.log('当前下载---->' , index);
                                    _this.currentIndex = index;
                                    // console.log("currentDownloader::" + _this.downloaderInfo.lessonName + "currentIndex::" + _this.currentIndex + " nowTotalSize:: " + _this.currentTotalSize + " receivedBytes:: " + receivedBytes);
                                    if (progressCallback) {
                                        let progressCallbackVal = {
                                            Code: "0",
                                            Message: "成功",
                                            ReturnValue: {
                                                DownloadSpeed: nowSpeed,
                                                Progress: ((_this.currentTotalSize + receivedBytes) * 100 / (_this.allFileSize)).toFixed()
                                            }
                                        }
                                        console.log(task.downloaderId + "progress::::::::::::: " ,  progressCallbackVal);
                                        vm.$store.commit('changecloudprogressVal', parseInt(progressCallbackVal.ReturnValue.Progress))
                                        progressCallback(JSON.stringify(progressCallbackVal));
                                    }
                                }, function () {//下载成功的回调
                                    //下载成功埋点
                                    console.log('当前下载成功--------------------------------------->' , task ,index);
                                    let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                                    DownloadCenter.getInstance().recordUserDownloadInfo({
                                        resourceType: task.downloadParam.FileType,
                                        resourceId: task.downloaderId,
                                        eduLevelId: user.eduLevelId,
                                        packageSize: fileDownloader.totalSize
                                    });
                                    //已经下载过的文件大小
                                    _this.currentTotalSize += fileDownloader.totalSize;
                                    console.log(task.downloaderId + " download success, currentTotalSize :: " + _this.currentTotalSize);
                                    if (fileDownloader.sourceName.endsWith(".zip")) {
                                        if(metaType === "BosVideo") {
                                            FileUtil.unzipFileAndRename(fileDownloader.sourceName, true, true, function () {
                                                resolve("success");
                                            }, function () {
                                                reject("error");
                                            });
                                        }else{
                                            FileUtil.unzipFileAndRename(fileDownloader.sourceName, true, true, function () {
                                                resolve("success");
                                            }, function () {
                                                reject("error");
                                            });
                                        }
                                    }else {
                                        resolve("success");
                                    }
                                }, function () {//下载失败的回调，失败记录失败值
                                    //已经下载过的文件大小
                                    _this.currentTotalSize += fileDownloader.totalSize;
                                    _this.errorDownloadTaskIndexes.push(index);
                                    window.$log.error("单个文件下载失败： downloaderId --> " + task.downloaderId);
                                    // console.log(task.downloaderId + " error, currentTotalSize :: " + _this.currentTotalSize);
                                    reject("error")
                                });
                            } else {
                                //即使文件存在也重新解压，防止因解压问题丢失文件，重新下载时可以重新进行解压
                                if (fileDownloader.sourceName.endsWith(".zip")) {
                                    if (metaType === "PolyvVideo") {
                                        FileUtil.unzipFileAndRename(fileDownloader.sourceName, false, false, function () {
                                            resolve("success");
                                        }, function () {
                                            reject("error");
                                        });
                                    } else {
                                        FileUtil.unzipFileAndRename(fileDownloader.sourceName, true, true, function () {
                                            resolve("success");
                                        }, function () {
                                            reject("error");
                                        });
                                    }
                                }else {
                                    resolve("success");
                                }
                                _this.currentTotalSize += currentFileSize;
                            }
                        })
                    })
                }
                downloadPromise.push(downloading);
            }
        });
        let gen = GeneratorFactory.createGenerator(downloadPromise);
        _this.genExecutor = new GeneratorExecutor();
        try {
            _this.genExecutor.run(gen, function () {
                if (successCallback) {
                    let successCallbackVal = {
                        ReturnValue: "complete"
                    }
                    successCallback(JSON.stringify(successCallbackVal));
                }
            },()=>{
                errorCallback();
            })
        } catch (e) {
            if (errorCallback) {
                errorCallback();
            }
        }
    }

    /**
     * 取消下载
     */
    cancelDownload() {
        if (this.singleDownloadTaskes.length > 0) {
            let currentTask = this.singleDownloadTaskes[this.currentIndex];
            let fileDownloader = null;
            if (currentTask.downloadParam.FileType === POLYV_VIDEO) {
                fileDownloader = currentTask.fileDownloader.fileDownloader
            } else {
                fileDownloader = currentTask.fileDownloader;
            }
            // 先停止执行器，不继续往下执行
            if (this.genExecutor) {
                this.genExecutor.pause();
            }
            //停止正在下载任务
            if (fileDownloader) {
                fileDownloader.pauseDownload();
            }

            //初始化相关变量
            this.errorDownloadTaskIndexes = [];
            this.currentTotalSize = 0;
            this.currentIndex = 0;
            this.genExecutor = null;
        }
    }

    /**
     * 重新初始化
     */
    resumeDownload(successCallback) {
        let _this = this;
        this.singleDownloadTaskes = [];
        this.errorDownloadTaskIndexes = [];
        this.allFileSize = 0;
        this.currentTotalSize = 0;
        this.currentIndex = 0;
        if(this.genExecutor){
            this.genExecutor.pause()
        }
        this.genExecutor = null;

        let promiseArr = []
        //构造函数初始化
        console.log("resumeDownload LessonId::>" + this.downloaderId + " 塞入下载队列的任务个数：" + this.downloadParames.length);
        this.downloadParames.forEach(downloadParam => {
            let construct = function () {
                return new Promise((resolve, reject) => {
                    let task = new SingleDownloadTask(downloadParam, function () {
                        if (task.fileDownloader.totalSize !== 0) {
                            _this.singleDownloadTaskes.push(task);
                            //获取总文件大小
                            _this.allFileSize += task.fileDownloader.totalSize;
                            window.$log.info("SingleDownloadTask init success downloaderId::> " + task.downloaderId);
                            resolve("success");
                        } else {
                            //为0的也push进去
                            _this.singleDownloadTaskes.push(task);
                            window.$log.info("SingleDownloadTask init error downloaderId::> " + task.downloaderId);
                            resolve("error");
                        }
                    });
                });
            }
            promiseArr.push(construct);
        });
        let gen = GeneratorFactory.createGenerator(promiseArr);
        let executor = new GeneratorExecutor();
        executor.run(gen, function () {
            if (successCallback) {
                successCallback();
            }
        })
    }
}
